/*
 * @Descripttion: 
 * @Author: zhangchong zc16607@gmail.com
 * @Date: 2023-02-27 16:08:44
 * @LastEditors: zhangchong zc16607@gmail.com
 * @LastEditTime: 2023-03-02 15:32:04
 */
const commonRes = require('../utils/commonRes')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt')
const fileDb = require('../utils/fileDb')

class Login {
  static async login(req, res) {
    
    let name = fileDb.getKey('username')
    let pwd = fileDb.getKey('password')
    if (req.body.username !== name) {
      return commonRes(res, null, { message: '账号或密码错误' })
    }
    // console.log('epwd', bcrypt.hashSync('admin', 10)) hash后字符串
    const isValidPassWord = await bcrypt.compare(
      req.body.password,
      pwd
    )
    if (!isValidPassWord) {
      return commonRes(res, null, { message: '账号或密码错误' })
    }
    //生成token,使用用户id
    const token = jwt.sign({
      id: String(name)
    }, 'express-auth', { expiresIn: '7d' })

    return commonRes(res, { name, token })
  }
}


module.exports = Login